package com.lovo.csc.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.csc.dto.ExpenseDto;
import com.lovo.csc.dto.PrepayDto;
import com.lovo.csc.entity.Deposit;
import com.lovo.csc.entity.Prepay;
import com.lovo.csc.entity.ReturnOrder;
import com.lovo.csc.service.IDepositService;
import com.lovo.csc.service.IPrepayService;
import com.lovo.csc.service.IReturnOrderService;
import com.lovo.dto.ReturnOrderDto;
import com.lovo.util.MQUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import rx.internal.util.LinkedArrayList;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 前端传回需要审核退款的客户订单 前端控制器
 * </p>
 *
 * @author lovo
 * @since 2022-07-07
 */
@RestController
@RequestMapping("/return-order")
@Api(tags = "退款退货订单操作层 文林挥 001")
public class ReturnOrderController {
    @Autowired
    IPrepayService prepayService;
    @Autowired
    IReturnOrderService service;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    IDepositService depositService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @ApiOperation(value = "通过用户编号查看退货订单")
    @GetMapping("findByUserCode")
    public List<ReturnOrder> findByUserCode(String userCode){
        QueryWrapper<ReturnOrder> qw=new QueryWrapper<>();
        qw.eq("user_code",userCode);
        return service.list(qw);
    }

    @ApiOperation(value="分页查看全部拖货订单")
    @GetMapping("findReturnOrder")
    public IPage findReturnOrder(int currentPage,int PageSize){
        IPage<ReturnOrder> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(PageSize);
        return service.page(page,null);
    }

    @ApiOperation(value = "退款订单信息保存")
    @PostMapping("auditOrder")
    @Transactional
    public String auditOrder(String orderCode){
        if (!redisTemplate.opsForHash().hasKey("returnOrder",orderCode)){
            return "订单不存在，或已处理";
        }
        Object obj = redisTemplate.opsForHash().get("returnOrder",orderCode);
        String s = JSON.toJSONString(obj);
        // 转化成退货实体
        ReturnOrderDto orderDto = JSON.parseObject(s,ReturnOrderDto.class);
        // 通过userCode得到prepay实体
        String userCode = orderDto.getUsername();
        QueryWrapper<Prepay> qw= new QueryWrapper<>();
        qw.eq("user_code",userCode);
        Prepay prepay=prepayService.getOne(qw);
        //  编写存款记录实体
        Deposit deposit = new Deposit();
        deposit.setPrepayId(prepay.getPrepayId());
        deposit.setUserCode(userCode);
        double money = orderDto.getRetuenprice();
        deposit.setSaveMoney((float) money);
        deposit.setSaveWay("退货退款");
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        deposit.setSaveTime(df.format(LocalDateTime.now()));
        depositService.save(deposit);
        // 余额加上退款金额
        prepay.setBalance( (prepay.getBalance() + money));
        prepayService.saveOrUpdate(prepay);
        // 保存退款订单

        ReturnOrder returnOrder = new ReturnOrder();
        returnOrder.setReturnCode(orderCode);
        returnOrder.setReturnPath("会员充值");
        returnOrder.setReturnTime(orderDto.getReturndate());
        returnOrder.setUserCode(userCode);
        returnOrder.setReturnState("已退款");
        returnOrder.setTotal((float) money);
        returnOrder.setGoodsCode(orderDto.getCommoditycode());
        returnOrder.setGoodsNum(orderDto.getCommodityNumber());
        // 处理完成 删除缓存中该订单
        redisTemplate.opsForHash().delete("returnOrder",orderCode);
        // 通知前后端人员
        rabbitTemplate.convertAndSend("fanoutExchangePrepay",null,orderDto);
        // 给前端充值人员信息
        ExpenseDto expenseDto = new ExpenseDto();
        expenseDto.setUserName(userCode);
        expenseDto.setMoney((float) money);
        rabbitTemplate.convertAndSend(MQUtil.PrepayExchange,"return.key",expenseDto);
        service.save(returnOrder);
        return "ok";
    }
    @ApiOperation(value = "待审核的退货订单")
    @GetMapping("getAudit")
    public Object getAudit(){
        boolean exist = redisTemplate.hasKey("returnOrder");
        if (exist){
            return redisTemplate.opsForHash().values("returnOrder");
        }
        return null;
    }

}
